<?php

namespace App\Service\Coin;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Model\PayOrder;
use App\Model\Setting\TmpSetting;
use App\Model\UserPayBlacklist;
use App\Service\BaseService;

/**
 * 创建充值订单
 */
class CreateOrderService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $newPay = $this->curVersion >= env('NEW_PAYWAY_VERSION', '1.0.0');
        $clientIp = $this->request->server('remote_addr');
        $coin = $this->request->input('recharge_coin', 0);
        $money = $this->request->input('pay_money', 0);
        $payChannel = $this->request->input('pay_channel', PayOrder::CHANNEL_WX);
        $subjectId = $this->request->input('subject_id', 1);
        //支付渠道：0-原生，1-杉德
        $payFrom = PayOrder::getPayWay($payChannel, $newPay);
        //充值来源
        $from = $this->request->input('from', 0);

        //支付宝暂时关闭
        if (!$newPay && $payChannel == PayOrder::CHANNEL_ALI && $this->appId != 6) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '支付宝暂未开通，请选择用微信充值～');
        }

        //订单前检测
        if (PayOrder::FROM_ACT_DISCOUNT == $from) {
            $check = $this->checkActOrder($userId, $money, $coin, $payChannel);
            $subjectId = $check['subject_id'] ?? 0;
        } else {
            $check = $this->checkOrder($money, $subjectId, $payChannel, $userId);
        }
        //检测不通过    
        if ($check['errcode']) return $this->setError($check['errcode'], $check['errmsg']);

        switch ($payFrom) {
            case PayOrder::PAY_FROM_NATIVE:
                $ret = PayOrder::createOrder($userId, $payChannel, $subjectId, $clientIp, $from);
                break;
            case PayOrder::PAY_FROM_SAND:
                $payChannel =  $payChannel == PayOrder::CHANNEL_WX
                    ? PayOrder::CHANNEL_SAND_WX
                    : PayOrder::CHANNEL_SAND_ALI;
                $ret = PayOrder::createOrder($userId, $payChannel, $subjectId, $clientIp, $from);
                break;
        }
        $ret['pay_from'] = $payFrom;
        log_user_result($userId, $ret);
        return $ret;
    }

    /**
     * 创建订单前检测
     */
    function checkOrder($money, $subjectId = 1, $payChannel = 'wechat', $userId)
    {
        if (!in_array($payChannel, PayOrder::CHANNEL_VALID)) {
            return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '支付方式有误~'];
        }
        $subject = ConfigUtil::getRecharge($subjectId, $payChannel);
        if (!$subject || $subject['rmb'] != $money) {
            return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '充值参数有误，请刷新页面重新提交订单~'];
        }

        //总充值限额
        // $allTotal = PayOrder::getSuccessTotal($userId);
        //当天充值限额
        // $todayTotal = PayOrder::getSuccessTotal($userId, date('Y-m-d'));
        //超过总限额
        // if (
        //     $allTotal >= TmpSetting::getPayTotal()
        //     && $todayTotal >= env('PAY_TOTAL_LMT_DAY', 50000)
        // ) {
        //     return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '您在平台充值金额已达上限，请适度消费，理性交友！'];
        // }

        // 当天充值限额
        $todayTotal = PayOrder::getSuccessTotal($userId, date('Y-m-d'));

        $payLimitTaotal = config('busi.pay_limit_taotal');
        if(isset($payLimitTaotal[$userId])){
            #获取充值总金额
            $allTotal = PayOrder::getSuccessTotal($userId);
            #获取当日限制总额
            $payLimitTaotaLday = config('busi.pay_limit_taotal_day') ;
            $limitDay = isset($payLimitTaotaLday[$userId]) ? $payLimitTaotaLday[$userId] : 60000;#当日充值总额
            $togetherTotal = $todayTotal+$money*100;
            if($allTotal>=$payLimitTaotal[$userId] && $togetherTotal>=$limitDay){
                return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '您当日充值已达上限，请适度消费，理性交友！'];
            }
        }

        // 限制用户ID
        $checkPayLimit = UserPayBlacklist::checkExclude($userId);

        $limitPay = config('busi.pay_limit');
        if ($checkPayLimit || (isset($limitPay[$userId]) && $todayTotal >= $limitPay[$userId])) {
            return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '您当日充值已达上限，请适度消费，理性交友！'];
        }
        return ['errcode' => 0];
    }

    /**
     * 创建订单前检测-活动充值
     */
    function checkActOrder($userId = 0, $money = 0, $coin = 0, $payChannel = 'wechat')
    {
        if (!in_array($payChannel, PayOrder::CHANNEL_VALID)) {
            return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '支付方式有误~'];
        }
        //是否首次充值
        if (!PayOrder::checkSuccessCount($userId)) $actConf = config('act.recharge.new');
        else {
            //是否今天有充值过
            if (PayOrder::checkSuccessCount($userId, date('Y-m-d'), true)) {
                return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '你今天已经充值过，无法参与优惠充值啦，请明天再来吧~'];
            }
            $actConf = config('act.recharge.old');
        }
        // if ($money != $actConf['new_price'] || $coin != $actConf['coin']) {
        //     return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '充值参数有误，请刷新页面重新提交订单~'];
        // }
        return ['errcode' => 0, 'subject_id' => $actConf['subject_id']];
    }
}
